import { resourceApiAliasConfig } from "@gd-accbuild-core/config";
const {
  resourceUrlKeyAlias,
  childrenKeyAlias,
  realPageFileKeyAlias,
  resourceTypeKeyAlias,
  resourcePermsKeyAlias,
  resourceNameAlias,
  resourceIconAlias,
  idKeyAlias,
  pidKeyAlias,
  resourcePermsKeyDefinedRule,
  targetKeyAlias,
  hasChildrenAlias,
  ordinalKeyAlias,
  uiOptionsKeyAlias,
  hackSuffixJumpStr,
  getJumpTargetVal,
  getJumpTargetReourcePermsKey,
  viewModel_field_uiOptions_searchFormItemUiConfigAlias,
  viewModel_field_uiOptions_tableColUiConfigAlias,
  viewModel_field_uiOptions_containerFormItemUiConfigAlias,
  vmConfigAlias,
  viewModel_field_fieldNameAlias,
} = resourceApiAliasConfig;
import {
  transName,
  mapKeysToTarget,
  cloneDeep,
} from "@gd-accbuild-core/config/utils";
const getSettingFieldConfig = ({ column, curBackendSettingField }) => {
  const fieldPaths = curBackendSettingField.split(".");
  let localColumn = column;
  let isPathExists = true;
  fieldPaths.forEach((fieldPath) => {
    if (localColumn.hasOwnProperty(fieldPath)) {
      localColumn = localColumn[fieldPath];
    } else {
      isPathExists = false;
    }
  });
  return {
    fieldVal: isPathExists ? localColumn : null,
    isPathExists,
  };
};
/**
 * 组件属性配置规则
 * 列出每个待配置属性的
 * 1. backendSettingFieldMapping - 后台配置的字段映射;不同的弹窗触发策略的后端字段映射
 * 2. valExpression - 对应事件 属性的值为 true 时 的表达式
 * 3. backendSettingIsWorked - 字段是否存在时的判断条件，与事件无关，Add、Edit事件的判断条件肯定相同
 * 4. default - 字段如果不存在时的默认值
 * 5. setDynmicMetaAttrByCurEventStrategyName - 事件触发后,修改对应需要切换的属性元数据
 * */
const getCommonSaveEditDialogAttrSettingRules = () => {
  return {
    isShow: {
      backendSettingFieldMapping: {
        buildInAddBtn: "propOptions.btnsformConfig.buildInAddBtn.isShow",
        buildInEditBtn: "propOptions.btnsformConfig.buildInEditBtn.isShow",
      },
      valExpression: (column, curBackendSettingField) => {
        const config = getSettingFieldConfig({
          column,
          curBackendSettingField,
        });
        return config.fieldVal ?? true;
      },
      backendSettingIsWorked: (column, curBackendSettingField) => {
        const config = getSettingFieldConfig({
          column,
          curBackendSettingField,
        });
        return config.isPathExists ?? false;
      },
      default: (eventStrategyNames) => eventStrategyNames, //默认都显示
      setDynmicMetaAttrByCurEventStrategyName: (el, strategyName) => {
        //console.log('==设置isShow回调==', el, strategyName);
        el.isShow =
          el?.dynmicMetaAttrSettings?.isShowWithEventNames?.includes(
            strategyName
          ) ?? true;
      },
    },
    readonly: {
      backendSettingFieldMapping: {
        buildInAddBtn: "propOptions.btnsformConfig.buildInAddBtn.readonly",
        buildInEditBtn: "propOptions.btnsformConfig.buildInEditBtn.readonly",
      },
      valExpression: (column, curBackendSettingField) => {
        const config = getSettingFieldConfig({
          column,
          curBackendSettingField,
        });
        return config.fieldVal ?? false;
      },
      backendSettingIsWorked: (column, curBackendSettingField) => {
        const config = getSettingFieldConfig({
          column,
          curBackendSettingField,
        });
        return config.isPathExists ?? false;
      },
      default: (eventStrategyNames) => [], //默认不只读
      setDynmicMetaAttrByCurEventStrategyName: (el, strategyName) => {
        !el.hasOwnProperty("componentAttr") ? (el.componentAttr = {}) : null;
        el.componentAttr.readonly =
          el?.dynmicMetaAttrSettings?.readonlyWithEventNames?.includes(
            strategyName
          ) ?? false;
      },
    },
    required: {
      backendSettingFieldMapping: {
        buildInAddBtn: "required",
        buildInEditBtn: "required",
      },
      valExpression: (column, curBackendSettingField) => {
        return false;
      },
      backendSettingIsWorked: (column, curBackendSettingField) =>
        column.hasOwnProperty(curBackendSettingField) &&
        !(
          column.uiOptions?.["dialog-form-item-ui-type"] &&
          column.uiOptions?.["dialog-form-item-ui-type"].startsWith("Customize")
        ),
      default: (eventStrategyNames) => [], //默认不要求
      setDynmicMetaAttrByCurEventStrategyName: (el, strategyName) => {
        //console.log('==设置required回调==',el,strategyName);
        const formItemMetaRule = cloneDeep(el?.rule ?? []);
        // 外部的required权重大于内部的
        const orgRequiredRuleIdx = formItemMetaRule.findIndex((el) =>
          el.hasOwnProperty("required")
        );
        if (
          orgRequiredRuleIdx === -1 &&
          el?.dynmicMetaAttrSettings?.requiredWithEventNames?.includes(
            strategyName
          )
        ) {
          formItemMetaRule.push({
            required: true,
            message: "字段不可为空.",
            trigger: el.type === "Input" ? "blur" : "change",
          }); // TODO:FIXME:要根据组件类型选择trigger
          el.rule = formItemMetaRule;
        }
      },
    },
    //自己本地的动态属性;不来自后端
    canCommit: {
      backendSettingFieldMapping: {
        buildInAddBtn: "canCommit",
        buildInEditBtn: "canCommit",
      },
      valExpression: (column, curBackendSettingField) => {
        return true;
      },
      backendSettingIsWorked: (column, curBackendSettingField) =>
        column.hasOwnProperty(curBackendSettingField) &&
        column[curBackendSettingField],
      default: (eventStrategyNames) => eventStrategyNames, //默认都提交
      setDynmicMetaAttrByCurEventStrategyName: (el, strategyName) => {
        el.canCommit =
          el?.dynmicMetaAttrSettings?.canCommitWithEventNames?.includes(
            strategyName
          ) ?? true;
      },
    },
    disabled: {
      backendSettingFieldMapping: {
        buildInAddBtn: "propOptions.btnsformConfig.buildInAddBtn.disabled",
        buildInEditBtn: "propOptions.btnsformConfig.buildInEditBtn.disabled",
      },
      valExpression: (column, curBackendSettingField) => {
        const config = getSettingFieldConfig({
          column,
          curBackendSettingField,
        });
        return config.fieldVal ?? false;
      },
      backendSettingIsWorked: (column, curBackendSettingField) => {
        const config = getSettingFieldConfig({
          column,
          curBackendSettingField,
        });
        return config.isPathExists ?? false;
      },
      default: (eventStrategyNames) => [], //默认不禁用
      setDynmicMetaAttrByCurEventStrategyName: (el, strategyName) => {
        //console.log('==设置disabled回调==',el, strategyName);
        !el.hasOwnProperty("componentAttr") ? (el.componentAttr = {}) : null;
        el.componentAttr.disabled =
          el?.dynmicMetaAttrSettings?.disabledWithEventNames?.includes(
            strategyName
          ) ?? false;
      },
    },
  };
};

/**
 * 把uiOptions.containerFormItemUiConfig.dynmicComponentConfig.buildInAddOrEditBtn.staticConfig.dynmicMetaAttrSettings
 * propOptions.btnsformConfig.buildInAddBtn
 */

/**
 * 新增/编辑弹窗不同的样式规则
 */
const componentAttrSettingRules = getCommonSaveEditDialogAttrSettingRules();
/**
 * 弹窗复用的时候,新增/编辑事件 样式会不一样,由这个方法确定
 */
export const getCurEventDynmicMetaAttrSettings = (el, strategyName) => {
  //遍历每个定制属性
  Object.keys(componentAttrSettingRules).forEach((curComponentAttrName) => {
    if (
      Array.isArray(
        el?.dynmicMetaAttrSettings?.[`${curComponentAttrName}WithEventNames`]
      )
    ) {
      componentAttrSettingRules[
        curComponentAttrName
      ].setDynmicMetaAttrByCurEventStrategyName(el, strategyName);
    }
  });
  return el;
};
/**
 * 新增编辑弹窗需要复用,但可能属性不同需要根据事件动态配属性
 */
const getSaveEditDialog_DynmicMetaAttrSettings_WhenKeyOnlyFromBackend = (
  column,
  eventStrategyNames = ["buildInAddBtn", "buildInEditBtn"]
) => {
  let dynmicMetaAttrSettings = {};
  //遍历每个定制属性
  Object.keys(componentAttrSettingRules)
    .filter((curComponentAttrName) =>
      ["isShow", "readonly", "disabled"].includes(curComponentAttrName)
    )
    .forEach((curComponentAttrName) => {
      let componentAttrName = curComponentAttrName;
      let componentAttrValDefault =
        componentAttrSettingRules[curComponentAttrName].default(
          eventStrategyNames
        );
      const backendSettingFieldMapping =
        componentAttrSettingRules[curComponentAttrName]
          .backendSettingFieldMapping;
      const valExpression =
        componentAttrSettingRules[curComponentAttrName].valExpression;
      const backendSettingIsWorked =
        componentAttrSettingRules[curComponentAttrName].backendSettingIsWorked;
      let curComponentAttrNameWithEventNames = [];
      //遍历事件
      eventStrategyNames.forEach((eventStrategyName) => {
        const curBackendSettingField =
          backendSettingFieldMapping[eventStrategyName];
        //console.log(valExpression(column, curBackendSettingField), column, curBackendSettingField, '比一比')
        //满足表达式则推入事件
        valExpression(column, curBackendSettingField)
          ? curComponentAttrNameWithEventNames.push(eventStrategyName)
          : null;
      });
      //动态属性是否强制来自后端,如果来自后端,则不能用默认属性
      const isDynmicMetaForceFromBackend = eventStrategyNames.some(
        (eventStrategyName) => {
          const curBackendSettingField =
            backendSettingFieldMapping[eventStrategyName];
          return backendSettingIsWorked(column, curBackendSettingField);
        }
      );
      //如果强制来自后端=false ,则使用默认事件
      dynmicMetaAttrSettings[`${componentAttrName}WithEventNames`] =
        isDynmicMetaForceFromBackend
          ? curComponentAttrNameWithEventNames
          : componentAttrValDefault;
    });
  return dynmicMetaAttrSettings;
};

/**
 * 跳转表格列 宽度
 */
const adjustTableColMeta = (column, tableColMeta, tabObjHolderConfig) => {
  const sortablePlaceolderWidth = column.isSort ? 30 : 0;
  if (column.dataType === "DateTime") {
    tableColMeta.type = tableColMeta?.type ?? "Text";
    tableColMeta.formatter = (row, column, cellValue, index) => {
      return cellValue ? cellValue.substring(0, 19).replace("T", " ") : "";
    };
    tableColMeta["min-width"] = 130 + sortablePlaceolderWidth;
  } else if (column.dataType === "boolean") {
    tableColMeta.type = "Switch";
  } else if (column.dataType === "Guid" || column.stringLength > 100) {
    tableColMeta["min-width"] = 100 + sortablePlaceolderWidth;
    tableColMeta["showOverflowTooltip"] = true;
  }
  if (tableColMeta.hasOwnProperty("tabHolder")) {
    tableColMeta["tabObj"] = tabObjHolderConfig[tableColMeta["tabHolder"]];
  }
};

/**
 * 获取某个字段的搜索表单、弹窗表单、表格 的 元数据
 * @param {Object} column 某一字段信息
 * @param {Object} tabObjHolderConfig 用于弹窗表单多标签的
 */
export default async ({
  column,
  tabObjHolderConfig,
  store,
  roles,
  isUseStaticResource,
  staticResource,
}) => {
  const propCode =
    column[resourceApiAliasConfig["viewModel_field_fieldNameAlias"]];
  const searchPropCode = column["searchPropCode"];
  const componentAttrType = ["int", "float", "number", "short"].includes(
    column.dataType
  )
    ? "number"
    : "text";

  const columnUiOptions = column?.[uiOptionsKeyAlias];
  const searchFormItemDynmicComponentConfig =
    columnUiOptions?.[viewModel_field_uiOptions_searchFormItemUiConfigAlias]?.[
      vmConfigAlias
    ] ?? {};
  let searchFormItemMeta = searchFormItemDynmicComponentConfig?.[
    "staticConfig"
  ] ?? {
    type: "Input",
    key: propCode,
    label: column.displayName,
    labelWidth: "0",
    componentAttr: {},
    dataType: column.dataType,
  };
  //搜索表单必加的字段
  searchFormItemMeta.key = propCode;
  searchFormItemMeta.label = column.displayName;
  searchFormItemMeta.dataType = column.dataType;
  searchFormItemMeta.isShow = roles.includes("admin")
    ? column["propOptions"]["searchformConfig"]?.isOutput &&
      (column["propOptions"]["searchformConfig"]?.isDefaultShow ?? false)
    : column["propOptions"]["searchformConfig"]?.["searchType"] !== 0;
  searchFormItemMeta.labelWidth = searchFormItemMeta?.labelWidth ?? "0";
  searchFormItemMeta.hasOwnProperty("componentAttr")
    ? null
    : (searchFormItemMeta.componentAttr = {});
  searchFormItemMeta.componentAttr.hasOwnProperty("type")
    ? null
    : (searchFormItemMeta.componentAttr.type = componentAttrType);

  //容器表单
  const dialogFormItemDynmicComponentConfig =
    columnUiOptions?.[
      viewModel_field_uiOptions_containerFormItemUiConfigAlias
    ]?.[vmConfigAlias] ?? {};

  const buildInAddOrEditBtnConfig =
    dialogFormItemDynmicComponentConfig.hasOwnProperty("buildInAddOrEditBtn")
      ? dialogFormItemDynmicComponentConfig.buildInAddOrEditBtn
      : {};

  let dialogFormItemMeta = buildInAddOrEditBtnConfig?.["staticConfig"] ?? {
    type: "Input",
    key: propCode,
    searchKey: searchPropCode,
    label: columnUiOptions?.displayName ?? column.displayName,
    componentAttr: {},
    dataType: column.dataType,
  };
  //弹窗表单 必加的字段
  dialogFormItemMeta.key = propCode;
  dialogFormItemMeta.searchKey = searchPropCode;
  dialogFormItemMeta.label = columnUiOptions?.displayName ?? column.displayName;
  dialogFormItemMeta.dataType = column.dataType;
  /////////////////
  if (!dialogFormItemMeta.hasOwnProperty("dynmicMetaAttrSettings")) {
    dialogFormItemMeta.dynmicMetaAttrSettings = {};
  }
  dialogFormItemMeta.dynmicMetaAttrSettings = {
    ...dialogFormItemMeta.dynmicMetaAttrSettings,
    ...getSaveEditDialog_DynmicMetaAttrSettings_WhenKeyOnlyFromBackend(column),
  };
  if (roles.includes("admin")) {
    const isShowInAddForm =
      column["propOptions"]["btnsformConfig"]["buildInAddBtn"].isOutput &&
      (column["propOptions"]["btnsformConfig"]["buildInAddBtn"]
        ?.isDefaultShow ??
        true);
    const isShowInEditForm =
      column["propOptions"]["btnsformConfig"]["buildInEditBtn"].isOutput &&
      (column["propOptions"]["btnsformConfig"]["buildInEditBtn"]
        ?.isDefaultShow ??
        true);
    //['buildInAddBtn', 'buildInEditBtn']
    const dynmicMetaIsShow = [];
    isShowInAddForm ? dynmicMetaIsShow.push("buildInAddBtn") : null;
    isShowInEditForm ? dynmicMetaIsShow.push("buildInEditBtn") : null;
    dialogFormItemMeta.dynmicMetaAttrSettings["isShowWithEventNames"] =
      dynmicMetaIsShow;
  }
  ////////////////
  dialogFormItemMeta.hasOwnProperty("componentAttr")
    ? null
    : (dialogFormItemMeta.componentAttr = {});
  dialogFormItemMeta.componentAttr.hasOwnProperty("type")
    ? null
    : (dialogFormItemMeta.componentAttr.type = componentAttrType);

  //console.log(dialogFormItemMeta,'dialogFormItemMeta=====')
  //表格
  const tableColumnDynmicComponentConfig =
    columnUiOptions?.[viewModel_field_uiOptions_tableColUiConfigAlias]?.[
      vmConfigAlias
    ] ?? {};
  let tableColMeta = tableColumnDynmicComponentConfig?.["staticConfig"] ?? {
    type: "RichText",
    key: propCode,
    searchKey: searchPropCode,
    label: column.displayName,
    componentAttr: {},
    dataType: column.dataType,
  };

  //表格 必加的字段
  tableColMeta.key = propCode;
  tableColMeta.searchKey = searchPropCode;
  tableColMeta.label = column.displayName;
  tableColMeta.sortable = column.isSort ? "custom" : undefined;
  tableColMeta.isShow = roles.includes("admin")
    ? column["propOptions"]["tableConfig"].isOutput &&
      (column?.["propOptions"]?.["tableConfig"]?.isDefaultShow ?? false)
    : column["propOptions"]["tableConfig"]?.isShow; // column?.isShow ??
  tableColMeta.isCustomField = column?.isCustomField ?? false; //是否自定义字段
  tableColMeta.hasOwnProperty("componentAttr")
    ? null
    : (tableColMeta.componentAttr = {});
  tableColMeta.componentAttr.hasOwnProperty("type")
    ? null
    : (tableColMeta.componentAttr.type = componentAttrType);
  adjustTableColMeta(column, tableColMeta, tabObjHolderConfig);

  ///////搜索表单、弹窗表单、表格 的 动态属性的配置;即 optionsConfig、labelFunc
  const searchFormItemDynmicConfig =
    searchFormItemDynmicComponentConfig?.["dynmicConfig"] ?? {};
  const dialogFormItemDynmicConfig =
    buildInAddOrEditBtnConfig?.["dynmicConfig"] ?? {};
  const tableColumnDynmicConfig =
    tableColumnDynmicComponentConfig?.["dynmicConfig"] ?? {};
  if (tableColumnDynmicConfig.hasOwnProperty("linkConfig")) {
    const targetJumpCode =
      tableColumnDynmicConfig.linkConfig.targetResourcePermsCode;
    let targetJumpPage = null;
    if (store?.state?.permissionInUserPages?.activePermissionInUserPages) {
      targetJumpPage = store.state.permissionInUserPages.pages.find(
        (page) => page.code === targetJumpCode
      );
    } else if (store && store.state.permission) {
      targetJumpPage = store.state.permission.pages.find(
        (page) => page.code === targetJumpCode
      );
    }
    if (targetJumpPage) {
      tableColMeta.link = targetJumpPage.targetResourceUrl;
    }
  }
  return {
    searchFormItemMeta,
    dialogFormItemMeta,
    tableColMeta,
    searchFormItemDynmicConfig,
    dialogFormItemDynmicConfig,
    tableColumnDynmicConfig,
    dialogFormItemDynmicComponentConfig,
  };
};
